<?php


namespace App\Http\Controllers\Admin;

use App\DTOS\Admin\SaleDTO;
use App\Exceptions\ServiceException;
use App\Exports\ExcelExport;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Services\Game\SaleService;
use App\Services\RestClientService;
use App\Utils\ResponseUtil;
use Maatwebsite\Excel\Facades\Excel;

class SaleController extends Controller
{
    private SaleService $saleCodeService;
    private RestClientService $resetClientService;

    /**
     * InviteCodeController constructor.
     * @param SaleService $saleCodeService
     * @param RestClientService $resetClientService
     */
    public function __construct(SaleService $saleCodeService,RestClientService $resetClientService)
    {
        $this->saleCodeService = $saleCodeService;
        $this->resetClientService = $resetClientService;
    }
    public function gen()
    {
        $num = (int)request()->num;
        $channelId = (int)request()->channelId;
        $name = request()->name;

        if ($num > 10000){
            return ResponseUtil::error("单次生成数量请勿超过1万");
        }
        $this->saleCodeService->gen($num,$channelId,$name);
        return ResponseUtil::success();
    }

    public function flushSaleAdmin(){
        $this->saleCodeService->flushSaleAdmin();
        return ResponseUtil::success();

    }

    public function paginate()
    {
        $dto = new SaleDTO(request()->all());
        $paginate = $this->saleCodeService->paginate($dto);
        $data = $paginate->items();
        foreach ($data as &$datum) {
            $datum['createdAt'] = (new \DateTime($datum['created_at']))->format("Y-m-d H:i:s");
        }
        $res = [];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function export(){
        $dto = new SaleDTO(request()->all());
        $paginate = $this->saleCodeService->paginate($dto);
        $excelRows = [
            ['邀请码','密码']
        ];
        foreach($paginate->items() as $datum){
            $excelRows[] = [
                $datum['code'],
                $datum['password']

            ];
        }
        $excel = new ExcelExport($excelRows);
        return Excel::download($excel, '邀请码列表.xlsx');
    }

    public function detail($id){

        $inviteCode = $this->saleCodeService->getById($id);

        return ResponseUtil::success($inviteCode);
    }

    public function edit($id)
    {
        $inviteCode = $this->saleCodeService->getById($id);
        $name = request()->get('name');
        $password = request()->get('password');
        $inviteCode->name = $name;
        $inviteCode->password = $password;
        $inviteCode->save();
        // resetPass
        $this->resetClientService->post("http://task:9502/sale/resetPass",['saleId'=>$id]);
        return ResponseUtil::success();
    }

}
